//
//  ZRBannerView.m
//  简书:https://www.jianshu.com/u/043e94ca450f
//
//  Created by 黄涛 on 2018/5/18.
//  Copyright © 2018年 zero. All rights reserved.
//  轮播图 核:CollectionView

#import "ZRBannerView.h"
#import "ZRPageControl.h"
#import "ZRBannerLayout.h"
#import "ZRCollectionViewCell.h"
#define Times 1000
@interface ZRBannerView () <UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSInteger _totalDataCount; //记录总 数据个数
}

@property (nonatomic , weak) NSTimer * timer;
@property (nonatomic , weak) ZRPageControl * pageCtrl;
@property (nonatomic , weak) UICollectionView * mainView;
@property (nonatomic , weak) UICollectionViewFlowLayout * flowLayout;
@property (nonatomic , strong) NSMutableArray * imgageArr;
@property (nonatomic , strong) NSMutableArray * titleArr;

@end

NSString * const id_cell = @"ZRCollectionViewCellh";
@implementation ZRBannerView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
         [self settingInit];
         [self addSubview:self.mainView];
         [self pageCtrl];
    }
    return self;
}

- (void)settingInit{
    
    _isEndless = YES;
    _isAutoRecycle = YES;
    _isShowPageCtrl = YES;
    _autoTimeInterval = 3;
    _pageCtrlPosition = mid_ZRPosition;
    _isShowTitleBgColor = NO;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    NSLog(@"边距 ： %f",self.margin);
    

    
    _mainView.frame = self.bounds;
    
    if (_margin <= 0) {
        _flowLayout.itemSize = self.bounds.size;
    }
    
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    
    
    
    CGSize pageCtrlSize = [_pageCtrl sizeForNumberOfPages:self.imgageArr.count];
    CGFloat pageCtrl_w = _pageCtrlPosition == mid_ZRPosition ? width : pageCtrlSize.width;
    CGFloat pageCtrl_h = _pageCtrlPosition == mid_ZRPosition ? 30 : 30;
    CGFloat pageCtrl_x = 0;
    switch (_pageCtrlPosition) {
        case mid_ZRPosition: pageCtrl_x = 0; break;
        case left_ZRPosition: pageCtrl_x = 10; break;
        case right_ZRPosition: pageCtrl_x = width - pageCtrlSize.width - 15; break;
        default: break;
    }
    
    _pageCtrl.frame = CGRectMake(pageCtrl_x, height - pageCtrl_h, pageCtrl_w, pageCtrl_h);
    
    if (_isAutoRecycle) [self timer];

    //初始化 位置
    if (_mainView.contentOffset.x == 0 && _totalDataCount > 0) {

        NSInteger initIndex = self.isEndless ? _totalDataCount * 0.5 : 0;
        
        UICollectionViewScrollPosition scrollPosition = _flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal ? UICollectionViewScrollPositionCenteredHorizontally : UICollectionViewScrollPositionCenteredVertically;
        
        [self.mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:initIndex inSection:0] atScrollPosition:scrollPosition animated:NO];
    }
    
}

#pragma mark - ----------------------- 生命周期 -----------------------
#pragma mark - ----------------------- 其他方法 -----------------------
#pragma mark - 设置数据
- (void)setImages:(NSArray *)images titles:(NSArray *)titles{
    
    [self.imgageArr addObjectsFromArray:images];
    [self.titleArr addObjectsFromArray:titles];
    
    _totalDataCount = _isEndless ? self.imgageArr.count * Times : self.imgageArr.count;
    _pageCtrl.numberOfPages = images.count;
    
    [self.mainView reloadData];

}

#pragma mark - 定时器方法（自动轮播）
- (void)automaticScroll{
    
    if (_totalDataCount == 0) return;
    NSInteger currentIndex = [self getCurrentIndex];
    [self setScrollIndex:currentIndex + 1];

    NSLog(@"当前图片下 : %ld",(long)currentIndex);
}

#pragma mark - 移除定时器
- (void)removeTimer{
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - 获取当前 下标
- (NSInteger)getCurrentIndex{
    
    NSIndexPath * currentIndexPath = [_mainView indexPathForItemAtPoint:CGPointMake(_mainView.contentOffset.x + _margin, 0)];
    
    return currentIndexPath.item;
}

#pragma mark - 更改当前位置
- (void)setScrollIndex:(NSInteger)index{
    
    if (!_isEndless) return;
    BOOL isAnimated = index >= _totalDataCount || index == 0 ? NO : YES;
    NSInteger toIndex = index >= _totalDataCount ? _totalDataCount * 0.5 : index;
    
    UICollectionViewScrollPosition scrollPosition = _flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal ? UICollectionViewScrollPositionCenteredHorizontally : UICollectionViewScrollPositionCenteredVertically;

    [self.mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:toIndex inSection:0] atScrollPosition:scrollPosition animated:isAnimated];

}

#pragma mark - 手动设置 滚动位置
- (void)makeScrollViewScrollToIndex:(NSInteger)index{
    
    if (self.isAutoRecycle) [self removeTimer];
    if (_totalDataCount == 0) return;

    [self setScrollIndex:_totalDataCount * 0.5 + index];
    //设置定时器
    if (self.isAutoRecycle) [self timer];
    
}

#pragma mark - PageCtrl 下标
- (int)getPageCtrlIndex{
    
    NSInteger index = [self getCurrentIndex];
    
    return (int)index % self.imgageArr.count;
}

#pragma mark - ----------------------- 代理方法 -----------------------

#pragma mark - CollectionView Delegate && DataSource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZRCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:id_cell forIndexPath:indexPath];
    cell.backgroundColor = ZRRandomColor;
    switch (_pageCtrlPosition) {
        case mid_ZRPosition:   cell.textAlign = NSTextAlignmentCenter; break;
        case left_ZRPosition:  cell.textAlign = NSTextAlignmentRight; break;
        case right_ZRPosition: cell.textAlign = NSTextAlignmentLeft; break;
        default: break;
    }
    cell.image = self.imgageArr[indexPath.item % self.imgageArr.count];
    cell.title = self.titleArr[indexPath.item % self.imgageArr.count];
    cell.isShowTitleBgColor = _isShowTitleBgColor;
    cell.titleColor = _titleColor;
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _totalDataCount;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.delegate respondsToSelector:@selector(bannerView:selectedItemIndex:)]) {
        
        [self.delegate bannerView:self selectedItemIndex:[self getPageCtrlIndex]];
        
    }
}



#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    self.pageCtrl.currentPage = [self getPageCtrlIndex];
    
}

//开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    if (self.isAutoRecycle) [self removeTimer];
}

//结束拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    

    if (self.isAutoRecycle) [self timer];
}

- (CGPoint)collectionView:(UICollectionView *)collectionView targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset{

    
    
    return CGPointMake(200, 100);
    
}


- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{

//    CGFloat targetX = (*targetContentOffset).x;
//    NSInteger targetPage = [self getCurrentIndex];
//    //  综合考虑velocity和targetContentOffset这两方面因素决定targetpage
//    if (velocity.x == 0) {
//        targetPage = (targetX + self.flowLayout.itemSize.width * 0.5)/self.flowLayout.itemSize.width;
//    } else {
//        NSInteger vote = 0;
//        vote = velocity.x>0 ? vote+1:vote-1;
//        vote = (scrollView.contentOffset.x-self.offsetXOnBeginDragging >0)? vote+1:vote-1;
//        if (vote>0 && (targetPage+1<self.indicator.numberOfPages)) {
//            targetPage++;
//        }
//        if (vote<0 && targetPage-1>=0) {
//            targetPage--;
//        }
//    }
//    //  根据民主投票决定的targetPage计算最终的targetContentOffset，设置targetContentOffset
//    CGPoint offset = CGPointMake(self.pageWidth*targetPage, 0);
//    *targetContentOffset = offset;

}


//不是人为拖拽scrollView导致滚动完毕
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    CGFloat offSet_xy = _flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal ? scrollView.contentOffset.x : scrollView.contentOffset.y;

    //防止 脑残无聊用户 拖拽到尽头 ~
    if (offSet_xy == (_totalDataCount - 1) * self.flowLayout.itemSize.width || offSet_xy == 0) {

        sleep(self.autoTimeInterval);
        offSet_xy == 0 ?
        [self setScrollIndex:_totalDataCount * 0.5 + 1]:
        [self setScrollIndex:_totalDataCount];
    }


    if ([self.delegate respondsToSelector:@selector(bannerView:scrollIndex:)]) {

        [self.delegate bannerView:self scrollIndex:[self getPageCtrlIndex]];
    }

    
}

//人为拖拽scrollView导致滚动完毕
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [self scrollViewDidEndScrollingAnimation:self.mainView];
}

#pragma mark - ----------------------- 活动监听 -----------------------


#pragma mark - ---------------------- set & get ----------------------
#pragma mark - Main CollectionView
- (UICollectionView *)mainView{
    if (!_mainView) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
        _flowLayout = flowLayout;
        
        
        UICollectionView * mainView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        mainView.backgroundColor = [UIColor clearColor];
        mainView.pagingEnabled = YES;
        mainView.showsHorizontalScrollIndicator = NO;
        mainView.showsVerticalScrollIndicator = NO;
        mainView.dataSource = self;
        mainView.delegate = self;
        mainView.scrollsToTop = NO;
        
        [mainView registerClass:[ZRCollectionViewCell class] forCellWithReuseIdentifier:id_cell];

        _mainView = mainView;
    }
    return _mainView;
}

#pragma mark - PageControl
- (ZRPageControl *)pageCtrl{
    if (!_pageCtrl) {
        ZRPageControl * pageCtrl = [[ZRPageControl alloc] init];
        pageCtrl.currentPage = 0;
        pageCtrl.pageIndicatorTintColor = [UIColor grayColor];
        pageCtrl.currentPageIndicatorTintColor = [UIColor blackColor];
        pageCtrl.size = CGSizeMake(30, 30);
        pageCtrl.selectedImgName = @"1187302";
        
        [self addSubview:pageCtrl];
        _pageCtrl = pageCtrl;
    }
    return _pageCtrl;
}

#pragma mark - 定时器
- (NSTimer *)timer{
    if (!_timer) {
        
        [self removeTimer];
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:_autoTimeInterval target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES];
        _timer = timer;
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        
    }
    return _timer;
}

#pragma mark - 数据源 初始化
- (NSMutableArray *)imgageArr{
    if (!_imgageArr) {
        _imgageArr = [[NSMutableArray alloc] init];
    }
    return _imgageArr;
}

- (NSMutableArray *)titleArr{
    if (!_titleArr) {
        _titleArr = [[NSMutableArray alloc] init];
    }
    return _titleArr;
}

#pragma mark - 是否自动播放
- (void)setIsAutoRecycle:(BOOL)isAutoRecycle{
    _isAutoRecycle = isAutoRecycle;
    
    isAutoRecycle ? [self timer] : [self removeTimer];
}


#pragma mark - 是否 无限循环
- (void)setIsEndless:(BOOL)isEndless{
    _isEndless = isEndless;
}

#pragma mark - 自动轮播时间间隔
- (void)setAutoTimeInterval:(NSTimeInterval)autoTimeInterval{
    _autoTimeInterval = autoTimeInterval;
    if (!_isAutoRecycle) return;
    [self removeTimer];
    [self timer];
}
#pragma mark - 是否显示 PageCtrl
- (void)setIsShowPageCtrl:(BOOL)isShowPageCtrl{
    _isShowPageCtrl = isShowPageCtrl;
    
    self.pageCtrl.hidden = !isShowPageCtrl;
}

#pragma mark - PageCtrl 选中颜色
- (void)setPageCtrlSelectedColor:(UIColor *)pageCtrlSelectedColor{
    _pageCtrlSelectedColor = pageCtrlSelectedColor;
    
    self.pageCtrl.currentPageIndicatorTintColor = pageCtrlSelectedColor;
}

#pragma mark - 标题 颜色
- (void)setTitleColor:(UIColor *)titleColor{
    _titleColor = titleColor;
}

#pragma mark - 是否显示标题背景色
- (void)setIsShowTitleBgColor:(BOOL)isShowTitleBgColor{
    _isShowTitleBgColor = isShowTitleBgColor;
}

#pragma mark - PageCtrl 常规颜色
- (void)setPageCtrlNomalColor:(UIColor *)pageCtrlNomalColor{
    _pageCtrlNomalColor = pageCtrlNomalColor;
    
    self.pageCtrl.pageIndicatorTintColor = pageCtrlNomalColor;
}

#pragma mark - PageCtrl 位置
- (void)setPageCtrlPosition:(ZRPageCtrlPosition)pageCtrlPosition{
    _pageCtrlPosition = pageCtrlPosition;
    [self.mainView reloadData];
    
}

#pragma mark - 滚动方向
- (void)setScrollDirection:(UICollectionViewScrollDirection )scrollDirection{
    _scrollDirection = scrollDirection;
    _flowLayout.scrollDirection = scrollDirection;
}

#pragma mark - 边距
- (void)setMargin:(CGFloat)margin{
    _margin = margin;
    
    if ( margin < 1) return;
    _mainView.pagingEnabled = NO;
    
    NSLog(@"轮播图 宽高 ：%f, %f",_mainView.width,_mainView.height);
    
    ZRBannerLayout * flowLayout = [[ZRBannerLayout alloc] init];
    flowLayout.scrollDirection = _flowLayout.scrollDirection;
    self.flowLayout = flowLayout;
    if (flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
        
        flowLayout.minimumLineSpacing = 10;
        flowLayout.itemSize = CGSizeMake( _mainView.width - 2 * margin,_mainView.height);
        flowLayout.sectionInset = UIEdgeInsetsMake(0, margin, 0, margin);
        
    }else{
        
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.itemSize = CGSizeMake(_mainView.width, _mainView.height - 2 * margin );
        flowLayout.sectionInset = UIEdgeInsetsMake(margin, 0, margin, 0);
    }
        [_mainView setCollectionViewLayout:flowLayout];
    

}


@end
